package com.socialsoftware.MediaCommunication.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.permissionx.guolindev.PermissionX;
import com.socialsoftware.MediaCommunication.model.CallMode;
import com.socialsoftware.MediaCommunication.model.CommunicationMessage;
import com.socialsoftware.MediaCommunication.model.MessageType;
import com.socialsoftware.MediaCommunication.service.ScreenCaptureService;
import com.socialsoftware.MediaCommunication.service.WebSocketService;
import com.socialsoftware.MediaCommunication.utils.Constants;
import com.socialsoftware.MediaCommunication.webrtc.WebRTCManager;
import com.socialsoftware.R;

import org.webrtc.SurfaceViewRenderer;
import org.webrtc.VideoTrack;

import java.util.ArrayList;
import java.util.List;

/**
 * Activity for screen sharing
 */
public class ScreenSharingActivity extends AppCompatActivity implements WebRTCManager.WebRTCListener {
    private static final String TAG = "ScreenSharingActivity";
    private static final int REQUEST_SCREEN_CAPTURE = 1001;

    private SurfaceViewRenderer remoteVideoView;
    private Button btnStop;
    private TextView tvRemoteUser;
    private ConstraintLayout sharingControlsLayout;

    private WebSocketService webSocketService;
    private WebRTCManager webRTCManager;
    private ScreenCaptureService screenCaptureService;
    private boolean isWebSocketServiceBound = false;
    private boolean isScreenServiceBound = false;
    private boolean isIncomingCall = false;
    private String targetUser;
    private String targetUsername;
    private boolean screenCapturePending = false;

    private final ServiceConnection webSocketServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            WebSocketService.WebSocketBinder binder = (WebSocketService.WebSocketBinder) service;
            webSocketService = binder.getService();
            isWebSocketServiceBound = true;
            
            // Initialize WebRTC manager
            webRTCManager = new WebRTCManager(ScreenSharingActivity.this, webSocketService, ScreenSharingActivity.this);
            webRTCManager.setCallMode(CallMode.SCREEN.getValue());
            webRTCManager.init();
            
            // Initialize video views
            initVideoViews();
            
            // 如果是被叫方，直接准备接收屏幕共享，无需请求屏幕捕获权限
            if (isIncomingCall && targetUser != null) {
                Log.d(TAG, "Preparing to receive screen share as receiver");
                // 显示远程用户名
                if (tvRemoteUser != null) {
                    tvRemoteUser.setText(targetUsername != null ? targetUsername : targetUser);
                }
                
                // 被叫方直接应答，准备接收主叫方的屏幕共享
                webRTCManager.answerCall(targetUser, CallMode.SCREEN.getValue());
            } else if (!isIncomingCall && targetUser != null) {
                // 如果是主叫方且已有目标用户，直接请求屏幕捕获权限
                requestScreenCapture();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            webSocketService = null;
            isWebSocketServiceBound = false;
        }
    };
    
    private final ServiceConnection screenCaptureServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            Log.d(TAG, "ScreenCaptureService connected");
            ScreenCaptureService.LocalBinder binder = (ScreenCaptureService.LocalBinder) service;
            screenCaptureService = binder.getService();
            isScreenServiceBound = true;
            
            if (screenCapturePending && webRTCManager != null) {
                screenCapturePending = false;
                
                Intent mediaProjectionIntent = screenCaptureService.getMediaProjectionIntent();
                if (mediaProjectionIntent != null) {
                    Log.d(TAG, "Setting screen capture intent to WebRTCManager");
                    webRTCManager.setScreenCaptureIntent(mediaProjectionIntent);
                    
                    // 主叫方获取到屏幕捕获权限后，发起通话请求并共享屏幕
                    if (!isIncomingCall && targetUser != null) {
                        Log.d(TAG, "Starting call as initiator with screen sharing");
                        webRTCManager.startCall(targetUser);
                    }
                } else {
                    Log.e(TAG, "Media projection intent is null");
                    Toast.makeText(ScreenSharingActivity.this, "无法获取屏幕捕获权限", Toast.LENGTH_SHORT).show();
                    stopScreenSharing();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "ScreenCaptureService disconnected");
            screenCaptureService = null;
            isScreenServiceBound = false;
        }
    };

    private final BroadcastReceiver webSocketReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.ACTION_WEBSOCKET_MESSAGE.equals(intent.getAction())) {
                String messageJson = intent.getStringExtra(Constants.EXTRA_MESSAGE_JSON);
                handleWebSocketMessage(messageJson);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen_sharing_activity);

        // Get intent data
        isIncomingCall = getIntent().getBooleanExtra("isIncoming", false);
        targetUser = getIntent().getStringExtra("contact_username");
        targetUsername = getIntent().getStringExtra("contact_name");
        
        if (targetUsername == null) {
            targetUsername = targetUser; // 如果没有名称，使用用户名作为显示名称
        }
        
        if (isIncomingCall) {
            targetUser = getIntent().getStringExtra(Constants.EXTRA_CALLER_NAME);
            targetUsername = targetUser; // 对于来电，使用用户名作为显示名称
            Log.d(TAG, "Incoming call from: " + targetUser);
        } else {
            Log.d(TAG, "Preparing to initiate screen sharing to: " + targetUser);
        }

        initViews();
        checkPermissions();
        
        setTitle("屏幕共享");
    }

    private void initViews() {
        remoteVideoView = findViewById(R.id.remote_video);
        btnStop = findViewById(R.id.btn_stop);
        tvRemoteUser = findViewById(R.id.tv_remote_user);
        sharingControlsLayout = findViewById(R.id.controls_layout);

        btnStop.setOnClickListener(v -> stopScreenSharing());
        
        // 设置远程用户名
        if (targetUsername != null) {
            tvRemoteUser.setText(targetUsername);
        }
    }

    private void initVideoViews() {
        if (webRTCManager != null) {
            remoteVideoView.init(webRTCManager.getEglBase().getEglBaseContext(), null);
        }
    }

    private void checkPermissions() {
        List<String> requiredPermissions = new ArrayList<>();
        for (String permission : Constants.REQUIRED_PERMISSIONS) {
            requiredPermissions.add(permission);
        }
        
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            requiredPermissions.add(android.Manifest.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION);
        }
        
        PermissionX.init(this)
                .permissions(requiredPermissions)
                .request((allGranted, grantedList, deniedList) -> {
                    if (allGranted) {
                        bindWebSocketService();
                        registerWebSocketReceiver();
                    } else {
                        Log.d("ScreenSharingActivity" ,"需要必要权限才能进行屏幕共享");
                        finish();
                    }
                });
    }

    private void bindWebSocketService() {
        Intent intent = new Intent(this, WebSocketService.class);
        bindService(intent, webSocketServiceConnection, Context.BIND_AUTO_CREATE);
    }

    private void registerWebSocketReceiver() {
        IntentFilter filter = new IntentFilter(Constants.ACTION_WEBSOCKET_MESSAGE);
        LocalBroadcastManager.getInstance(this).registerReceiver(webSocketReceiver, filter);
    }

    private void handleWebSocketMessage(String message) {
        try {
            CommunicationMessage commMessage = CommunicationMessage.fromJson(message);
            String type = commMessage.getType();
            
            if (MessageType.OFFER.getValue().equals(type)) {
                webRTCManager.handleOffer(commMessage.getSdp(), commMessage.getMode());
            } else if (MessageType.ANSWER.getValue().equals(type)) {
                webRTCManager.handleAnswer(commMessage.getSdp());
            } else if (MessageType.ICE.getValue().equals(type)) {
                webRTCManager.handleIceCandidate(
                        commMessage.getSdpMid(),
                        commMessage.getSdpMLineIndex(),
                        commMessage.getCandidate());
            } else if (MessageType.CALL_BACK.getValue().equals(type)) {
                if ("1".equals(commMessage.getMsg())) {
                    // 被叫方接受通话，如果是主叫方，则继续创建offer
                    if (!isIncomingCall) {
                        Log.d(TAG, "Call accepted, creating offer");
                        webRTCManager.createOffer();
                    }
                } else {
                    // 被叫方拒绝通话
                    runOnUiThread(() -> Toast.makeText(this, "对方拒绝了屏幕共享", Toast.LENGTH_SHORT).show());
                    stopScreenSharing();
                }
            } else if (MessageType.HANGUP.getValue().equals(type)) {
                // 对方挂断
                runOnUiThread(() -> {
                    Toast.makeText(this, "对方已结束屏幕共享", Toast.LENGTH_SHORT).show();
                    if (webRTCManager != null) {
                        webRTCManager.cleanup();
                    }
                    finish();
                });
            }
        } catch (Exception e) {
            Log.e(TAG, "Error handling WebSocket message", e);
        }
    }

    private void requestScreenCapture() {
        Log.d(TAG, "Requesting screen capture permission");
        MediaProjectionManager projectionManager = 
                (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        startActivityForResult(
                projectionManager.createScreenCaptureIntent(),
                REQUEST_SCREEN_CAPTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SCREEN_CAPTURE) {
            if (resultCode == RESULT_OK && data != null) {
                Log.d(TAG, "Screen capture permission granted");
                
                // 启动屏幕捕获服务
                Intent serviceIntent = new Intent(this, ScreenCaptureService.class);
                serviceIntent.putExtra("data", data);
                
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    startForegroundService(serviceIntent);
                } else {
                    startService(serviceIntent);
                }
                
                bindService(serviceIntent, screenCaptureServiceConnection, Context.BIND_AUTO_CREATE);
                screenCapturePending = true;
                
                // 更新UI
                btnStop.setVisibility(View.VISIBLE);
                
                // 发送呼叫请求给被叫方
                if (!isIncomingCall && webSocketService != null) {
                    // 注意：实际的呼叫请求会在screenCaptureServiceConnection连接后发送
                    // 因为需要先获取屏幕捕获权限
                    Log.d(TAG, "Will send call request after screen capture service is connected");
                }
            } else {
                Toast.makeText(this, "屏幕捕获权限被拒绝，无法进行屏幕共享", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    private void stopScreenSharing() {
        if (webRTCManager != null) {
            webRTCManager.hangup();
        }
        
        // 停止屏幕捕获服务
        if (isScreenServiceBound && screenCaptureService != null) {
            unbindService(screenCaptureServiceConnection);
            isScreenServiceBound = false;
        }
        
        Intent serviceIntent = new Intent(this, ScreenCaptureService.class);
        stopService(serviceIntent);
        
        finish();
    }

    @Override
    public void onLocalVideoReady(VideoTrack videoTrack) {
        // 屏幕共享时不显示本地预览（因为是自己的屏幕）
        Log.d(TAG, "Local video track ready, but not showing preview for screen sharing");
    }

    @Override
    public void onRemoteVideoReady(VideoTrack videoTrack) {
        runOnUiThread(() -> {
            Log.d(TAG, "Remote video track ready, adding to remote view");
            videoTrack.addSink(remoteVideoView);
        });
    }

    @Override
    public void onCallConnected() {
        runOnUiThread(() -> {
            Toast.makeText(this, "屏幕共享连接已建立", Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    public void onCallDisconnected() {
        runOnUiThread(() -> {
            Toast.makeText(this, "屏幕共享已断开", Toast.LENGTH_SHORT).show();
            stopScreenSharing();
        });
    }

    @Override
    public void onError(String error) {
        runOnUiThread(() -> {
            Toast.makeText(this, "错误: " + error, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "WebRTC error: " + error);
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        
        // 注销广播接收器
        LocalBroadcastManager.getInstance(this).unregisterReceiver(webSocketReceiver);
        
        // 解绑服务
        if (isWebSocketServiceBound) {
            unbindService(webSocketServiceConnection);
            isWebSocketServiceBound = false;
        }
        
        if (isScreenServiceBound) {
            unbindService(screenCaptureServiceConnection);
            isScreenServiceBound = false;
        }
        
        // 停止屏幕捕获服务
        Intent serviceIntent = new Intent(this, ScreenCaptureService.class);
        stopService(serviceIntent);
        
        // 清理WebRTC资源
        if (webRTCManager != null) {
            webRTCManager.release();
            webRTCManager = null;
        }
    }
} 